<?php

namespace fize\think\facade;

use think\facade\Config;
use think\facade\Db as DbFacade;

/**
 * DB扩展
 */
class Db extends DbFacade
{

    /**
     * 对完整的SQL语句进行分页
     * @param string $sql    SQL完整语句
     * @param int    $offset 偏移量
     * @param int    $limit  每页数量
     * @param array  $params 占位符参数
     * @return array [总记录数, 记录数组]
     */
    public static function getPaginator(string $sql, int $offset, int $limit, array $params = []): array
    {
        $full_sql = substr_replace($sql, " SQL_CALC_FOUND_ROWS ", 6, 0);
        $full_sql .= " LIMIT $offset,$limit";
        $rows = self::query($full_sql, $params);
        $cout_sql = 'SELECT FOUND_ROWS() AS `hr_count`';
        $crw = self::query($cout_sql);
        $count = $crw[0]['hr_count'];
        return [$count, $rows];
    }

    /**
     * 根据字段扩展数组，未在数组里的字段则以默认值填充
     * @param array  $row       原数组
     * @param string $tableName 数据库表名
     * @return array
     */
    public static function fullFields(array $row, string $tableName): array
    {
        $prefix = Config::get('database.connections.mysql.prefix');
        $field = Db::query("show COLUMNS FROM " . $prefix . $tableName);
        $fields = [];
        foreach ($field as $value) {
            $fields[$value['Field']] = $value;
        }

        foreach ($fields as $key => $field) {
            if (!isset($row[$key])) {
                $row[$key] = $field['Default'];
            }
        }
        return $row;
    }

}